<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('system_logs', function (Blueprint $table) {
            // 添加新的字段
            $table->string('username', 100)->nullable()->after('user_id')->comment('操作用户名');
            $table->string('operation_type', 50)->nullable()->after('action')->comment('操作类型');
            $table->string('operation_name', 100)->nullable()->after('operation_type')->comment('操作名称');
            $table->string('request_method', 10)->nullable()->after('user_agent')->comment('请求方法');
            $table->text('request_url')->nullable()->after('request_method')->comment('请求URL');
            $table->json('request_data')->nullable()->after('request_url')->comment('请求数据');
            $table->unsignedSmallInteger('response_status')->nullable()->after('context')->comment('响应状态码');
            $table->text('response_message')->nullable()->after('response_status')->comment('响应消息');
            $table->string('source', 50)->default('web')->after('response_message')->comment('日志来源');
            $table->string('session_id', 100)->nullable()->after('source')->comment('会话ID');
            $table->decimal('duration', 8, 2)->nullable()->after('session_id')->comment('请求耗时(毫秒)');

            // 更新索引
            $table->index(['operation_type', 'created_at']);
            $table->index(['module', 'created_at']);
            $table->index(['ip_address', 'created_at']);
            $table->index(['session_id']);

            // 使用Invisible Indexes优化查询性能
            $table->index(['user_id', 'action', 'created_at'])->invisible();
            $table->index(['module', 'level', 'created_at'])->invisible();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('system_logs', function (Blueprint $table) {
            // 删除添加的字段
            $table->dropColumn([
                'username',
                'operation_type',
                'operation_name',
                'request_method',
                'request_url',
                'request_data',
                'response_status',
                'response_message',
                'source',
                'session_id',
                'duration',
            ]);

            // 删除索引
            $table->dropIndex(['operation_type', 'created_at']);
            $table->dropIndex(['module', 'created_at']);
            $table->dropIndex(['ip_address', 'created_at']);
            $table->dropIndex(['session_id']);
        });
    }
};
